let state = {number: 0};
let updateQueue = [];

function setState(newState) {
    updateQueue.push(newState)
}

setState({number: state.number + 1});
setState({number: state.number + 1});
setState({number: state.number + 1});

updateQueue.forEach(newState => state = newState);
console.log(state);


//setState----批量更新---缓存实现原理
class Component {
    constructor() {
        this.state = {number: 0};
        this.batchUpdate = false;
        this.updateQueue = [];
        this.callbackQueue = []

    }

    setState = (partialState, callback) => {
        if (this.batchUpdate) {
            this.updateQueue.push(partialState);
            if (callback)
                this.callbackQueue.push(callback);

        } else {
            // setTimeout等不走批处理，实时更新
            // 判断setstate的参数是对象还是函数 【setstate的参数既可以是函数也可以是对象】 （优雅写代码）

            this.state = typeof partialState == 'function' ? partialState(this.state) : partialState;
            /* if (typeof partialState == 'function')
                 this.state = partialState(this.state)
             else
                 this.state = partialState;*/
        }

    };
    flush = () => {

        let state = this.state;
        for (let i = 0; i < this.updateQueue.length; i++) {
            //把部分修改的值直接赋值给了this.state,改了那个属性就传哪个属性。导致原本没有变化的state属性没有在state里面
            let partialState = typeof this.updateQueue[i] == 'function' ? this.updateQueue[i](this.state) : this.updateQueue[i];
            state = {...state, ...partialState};     //state里面的属性只能增加或者修改，不可以删除

        }
        this.state = state;
        this.callbackQueue.forEach(callback => callback());
        // this.updateQueue.forEach(newState => state = newState);
        this.batchUpdate = false;   //调整为批量更新


    };

    add = () => {
        setTimeout(() => {
            this.setState({number: this.state.number + 3})
            console.log(this.state)
        })

        this.batchUpdate = true;   //调整为批量更新
        // this.setState({number: this.state.number + 1});
        // this.setState({number: this.state.number + 1});
        // this.setState({number: this.state.number + 1});

        this.flush()
    }

}


let c = new Component();
c.add();
console.log(c.state)
